package com.moli.iov.base.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.base.cache.redis.SysParamSettingsCacheService;
import com.moli.iov.base.enums.ParamUnitEnum;
import com.moli.iov.base.enums.SysParamSettingEnum;
import com.moli.iov.base.mapper.SysParamSettingsMapper;
import com.moli.iov.base.model.SysParamSettingsParam;
import com.moli.iov.base.model.dto.SysParamSettingsCacheBean;
import com.moli.iov.base.model.dto.req.SysParamSettingsQueryReqDto;
import com.moli.iov.base.model.dto.res.SysParamSettingsResDto;
import com.moli.iov.base.model.po.SysParamSettings;
import com.moli.iov.base.service.ISysParamSettingsService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.enums.UserTypeEnum;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.ValidationUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统参数设置  服务实现类
 * </p>
 *
 * @author wanghualin
 * @since 2019-10-08
 */
@Service
public class SysParamSettingsServiceImpl extends
    ServiceImpl<SysParamSettingsMapper, SysParamSettings> implements ISysParamSettingsService {

  @Autowired
  private SysParamSettingsCacheService settingsCacheService;


  @Override
  public void updateSysParamSettings(SysParamSettings sysParamSettings) {
    settingsCacheService.deleteSysParamSettings(sysParamSettings.getCompanyId());
    boolean b = this.saveOrUpdate(sysParamSettings);
    if (b) {
      SysParamSettingsParam param = new SysParamSettingsParam();
      param.queryEqCompanyId(sysParamSettings.getCompanyId());
      List<SysParamSettings> list = this.list(param.get());
      if (!CollectionUtils.isEmpty(list)) {
        SysParamSettingsCacheBean bean = assembleSysParamSettingsCacheBean(list,
            sysParamSettings.getCompanyId());
        settingsCacheService.setSysParamSettings(bean);
      }
    }
  }

  @Override
  public SysParamSettings getSysParamSettingsById(Long id) {
    return this.getById(id);
  }

  @Override
  public PageExtend<SysParamSettingsResDto> listSysParamSettings(SysParamSettingsQueryReqDto reqDto) {
    ValidationUtils.validateBean(reqDto);
    SysParamSettingsParam param = new SysParamSettingsParam();
    if (reqDto.getSysUserType().intValue() == UserTypeEnum.COMPANY.getFlag()) {
      param.queryEqCompanyId(reqDto.getSysCompanyId());
    } else {
      param.queryEqCompanyId(reqDto.getCompanyId());
    }
    param.queryEqParamCode(reqDto.getParamCode());
    IPage<SysParamSettings> page = new Page(reqDto.getPageNum(), reqDto.getPageSize());
    IPage<SysParamSettings> list = super.page(page, param.get());
    return assembleSysParamSettingsResDto(list);
  }

  @Override
  public List<SysParamSettings> getSysParamSettingsByCompanyId(Long companyId) {
    SysParamSettingsParam param = new SysParamSettingsParam();
    param.queryEqCompanyId(companyId);
    return this.list(param.get());
  }

  @Override
  public void saveBatchSysParamSettings(List<SysParamSettings> settingsList, Long companyId) {
    boolean b = this.saveBatch(settingsList);
    if (b) {
      SysParamSettingsCacheBean bean = assembleSysParamSettingsCacheBean(settingsList, companyId);
      settingsCacheService.setSysParamSettings(bean);
    }
  }


  @Override
  public Map<String, String> listSysParamSettingsCacheBean() {
    Map<String, String> map = settingsCacheService
        .listSysParamSettings();
    if (!CollectionUtils.isEmpty(map)) {
      return map;
    } else {
      SysParamSettingsParam param = new SysParamSettingsParam();
      List<SysParamSettings> list = this.list(param.get());
      if (!CollectionUtils.isEmpty(list)) {
        List<SysParamSettingsCacheBean> cacheBeans = new ArrayList<>();
        list.stream().collect(Collectors.groupingBy(SysParamSettings::getCompanyId)).
            forEach((aLong, sysParamSettings) -> {
              cacheBeans.add(assembleSysParamSettingsCacheBean(sysParamSettings, aLong));
            });
        settingsCacheService.saveBatchCache(cacheBeans);
        return settingsCacheService
            .listSysParamSettings();
      }
      return null;
    }
  }

  @Override
  public void cleanSysParamSettingsCache() {
    settingsCacheService.cleanSysParamSettingsCache();
  }

  @Override
  public void initSysParamSettings() {
    //清空缓存
    settingsCacheService.cleanSysParamSettingsCache();
    //添加缓存
    SysParamSettingsParam param = new SysParamSettingsParam();
    List<SysParamSettings> list = this.list(param.get());
    if (!CollectionUtils.isEmpty(list)) {
      List<SysParamSettingsCacheBean> cacheBeans = new ArrayList<>();
      list.stream().collect(Collectors.groupingBy(SysParamSettings::getCompanyId)).
          forEach((aLong, sysParamSettings) -> {
            cacheBeans.add(assembleSysParamSettingsCacheBean(sysParamSettings, aLong));
          });
      settingsCacheService.saveBatchCache(cacheBeans);

    }
  }

  /**
   * 组装缓存Bean
   */
  public SysParamSettingsCacheBean assembleSysParamSettingsCacheBean(
      List<SysParamSettings> settingsList, Long companyId) {
    if (!CollectionUtils.isEmpty(settingsList) && companyId != null) {
      SysParamSettingsCacheBean bean = new SysParamSettingsCacheBean();
      bean.setCompanyId(companyId.toString());
      for (SysParamSettings settings : settingsList) {
        if (settings.getParamCode().equals(SysParamSettingEnum.SOC.getDictCode())) {
          bean.setSoc(settings.getParamValue());
        } else if (settings.getParamCode()
            .equals(SysParamSettingEnum.LOW_VOLTAGE_V.getDictCode())) {
          bean.setLowVoltage(settings.getParamValue());
        } else if (settings.getParamCode()
            .equals(SysParamSettingEnum.OFFLINE_ALARM_DURATION.getDictCode())) {
          bean.setOfflineAlarmDuration(settings.getParamValue());
        } else if (settings.getParamCode()
            .equals(SysParamSettingEnum.FENCE_ALARM_DURATION.getDictCode())) {
          bean.setFenceAlarmDuration(settings.getParamValue());
        } else if (settings.getParamCode()
            .equals(SysParamSettingEnum.MILEAGE_ALARM_DURATION.getDictCode())) {
          bean.setMileageAlarmDuration(settings.getParamValue());
        } else if (settings.getParamCode()
            .equals(SysParamSettingEnum.IGNORE_ALARM_DURATION.getDictCode())) {
          bean.setIgnoreAlarmDuration(settings.getParamValue());
        }
      }
      return bean;
    }
    return null;
  }

  /**
   * 组装
   */
  public PageExtend<SysParamSettingsResDto> assembleSysParamSettingsResDto(
      IPage<SysParamSettings> list) {
    if (list != null && !CollectionUtils.isEmpty(list.getRecords())) {
      PageExtend<SysParamSettingsResDto> res = new PageExtend<>();
      res.setPageSize(list.getSize());
      res.setTotal(list.getTotal());
      res.setPageNumber(list.getCurrent());
      List<SysParamSettingsResDto> resDtos = new ArrayList<>();
      for (SysParamSettings record : list.getRecords()) {
        SysParamSettingsResDto dto = new SysParamSettingsResDto();
        CommonUtils.copyProperties(record, dto);
        dto.setParamValueStr(dto.getParamValue() + ParamUnitEnum.getCodeName(dto.getParamUnit()));
        resDtos.add(dto);
      }
      res.setRecords(resDtos);
      return res;
    }
    return new PageExtend<>();
  }
}
